<?php


namespace app\api\controller;


use Aliyun\Core\DefaultAcsClient;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\Regions\EndpointConfig;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use think\Session;
use think\Validate;

class Common extends Controller
{

    static $acsClient = null;


    /**
     * 数据字典，查询字典
     * @param $keword
     * @return mixed
     */
    public function dictionary($keword=0,$type=0){
        $where['status'] = 1;
        if(!empty($type)){
            $where['type'] = $type;
        }

        $black = Db::name($keword)->where($where)->field("id,name")->select();
        $data = [];
        foreach ($black as $k=>$v){
            $data[] = ['value'=>$v['id'],'title'=>$v['name']];
        }
        return $data;
    }

    /**
     * 模拟登录
     */
    public function testusername($uid){
        $user = Db::name("project_account")->where(['id'=>$uid])->field("id,name,mobile,fans_id,survey,statisticsAuto,expose")->find();
        return $user;
    }


    /**
     * 取得AcsClient
     *
     * @return DefaultAcsClient
     */
    public function showappid($appid){
        $config = Db::name("config")->where(['xcx_appid'=>$appid])->find();
        return $config;
    }

    /**
     * a验证
     * @param $data
     * @param $rule
     * @throws Exception
     */
    public function condition($data,$rule){
        $validate = new Validate($rule);
        if (!$validate->check($data)) {
            throw new Exception($validate->getError());
        }
    }

    public function getAcsClient() {
        //产品名称:云通信短信服务API产品,开发者无需替换
        $product = "Dysmsapi";

        //产品域名,开发者无需替换
        $domain = "dysmsapi.aliyuncs.com";

        // TODO 此处需要替换成开发者自己的AK (https://ak-console.aliyun.com/)
        $accessKeyId = "LTAI4GB9k79kJpiXWDVss7oH"; // AccessKeyId

        $accessKeySecret = "6EOHKvJ3AjBf5dE56zIXcxqNEEyhBq"; // AccessKeySecret

        // 暂时不支持多Region
        $region = "cn-hangzhou";

        // 服务结点
        $endPointName = "cn-hangzhou";


        if(static::$acsClient == null) {
            //初始化acsClient,暂不支持region化
            $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
            // 手动加载endpoint
            EndpointConfig::load();
            // 增加服务结点
            DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);
            // 初始化AcsClient用于发起请求
            static::$acsClient = new DefaultAcsClient($profile);
        }
        return static::$acsClient;
    }

    /**
     * 查询配置选项
     * @param $key
     * @return array|mixed
     * @author zhixuedong
     * @date 2021/1/20/020
     */
    public function publicAttribute($key){
        //服务类型
        $data = Db::name("config_attribute")->where(['key'=>$key])->value("value");
        $data = explode("|",$data);
        foreach ($data as $k=>$v){
            $data[$k+1] = $v;
        }
        unset($data[0]);
        return $data;
    }

    public function handle($table,$data){
        if(empty($data['id'])){
            $id = Db::name($table)->insertGetId($data);
        }else{
            $id = $data['id'];
            Db::name($table)->where(['id'=>$id])->update($data);
        }
        return $id;
    }

    /**
     * 查询条件
     * @author zhixuedong
     * @date 2021/1/20/020
     */
    public function public_select($table,$where,$field=null,$start=0,$limit=0){
        $data = Db::name($table)->where($where);
        if($start!=0 & $limit!=0){
            $data = $data->limit($start,$limit);
        }
        if(!empty($field)){
            $data = $data->field($field);
        }
        return $data;
    }


    /**
     * description：计算离活动结束还剩多久时间
     * @param string $date
     * @return array
     */
    function timer($date='2018-06-23'){
        $t = strtotime($date)-time();//单位"秒"
        $arr = [];
        $day = intval($t/86400);//天
        $arr['day'] = $day;
        $hour = intval((($t/86400)-$day)*24);//小时
        $arr['hour'] = $hour;
        $minute = intval( (((($t/86400)-$day)*24)-$hour)*60 );//分钟
        $arr['minute'] = $minute;
        $second = intval(((((((($t/86400)-$day)*24)-$hour)*60)-$minute)*60));//秒
        $arr['second'] = $second;
        return $day."天".$hour."小时".$minute."分钟".$second."秒";
    }





    public function common(){
        if(empty($_POST['userid'])){
            $userid = Session::get("userid");
        }else{
            $userid = $_POST['userid'];
            Session::set("userid",$userid);
        }

//        $userid = 1; //测试环境
//        $appid = "wxcb4dcc3c92223702";
//        $config = Db::name("config")->where(['xcx_appid'=>$appid])->find();
//        Session::set("thisWechat",$config);

        $fans = Db::name("admin_fans")->where(['id'=>$userid])->find();
        if(empty($fans)){
            $black['code'] = 1;
            $black['msg'] = "请登录";
            echo json_encode($black);die;
        }
        return $userid;
    }


    //记录添加账号信息
    public function addAccountData($data)
    {
        Db::name("admin_account_data")->insert($data);
    }

    //记录添加账号信息(修改)
    public function updateAccountData($data, $table, $id)
    {
        Db::name("admin_account_data")->where(['table' => $table, 'table_id' => $id])->update($data);
    }

    //查询省市区id
    public function findregionId($name){
        $id = Db::name("admin_region")->where(['name'=>$name])->value("id");
        return $id;
    }

    //解析地址
    public function handleAddress($address)
    {
        preg_match('/(.*?(省|自治区|北京市|天津市))/', $address, $matches);
        if (count($matches) > 1) {
            $province = $matches[count($matches) - 2];
            $address = str_replace($province, '', $address);
        }
        preg_match('/(.*?(市|自治州|地区|区划|县))/', $address, $matches);
        if (count($matches) > 1) {
            $city = $matches[count($matches) - 2];
            $address = str_replace($city, '', $address);
        }
        preg_match('/(.*?(市|区|县|镇|乡|街道))/', $address, $matches);
        if (count($matches) > 1) {
            $area = $matches[count($matches) - 2];
            $address = str_replace($area, '', $address);
        }
        return [
            'province' => isset($province) ? $province : '',
            'city' => isset($city) ? $city : '',
            'area' => isset($area) ? $area : '',
        ];
    }


    //验证手机格式
    function isMobile($mobile) {
        if (!is_numeric($mobile)) {
            return false;
        }
        return preg_match('#^1[3,4,5,6,7,8,9]{1}[\d]{9}$#', $mobile) ? true : false;
    }


    //验证身份证
    public static function setCard($card)
    {
        $city = [11 => "北京", 12 => "天津", 13 => "河北", 14 => "山西", 15 => "内蒙古", 21 => "辽宁", 22 => "吉林", 23 => "黑龙江 ", 31 => "上海", 32 => "江苏", 33 => "浙江", 34 => "安徽", 35 => "福建", 36 => "江西", 37 => "山东", 41 => "河南", 42 => "湖北 ", 43 => "湖南", 44 => "广东", 45 => "广西", 46 => "海南", 50 => "重庆", 51 => "四川", 52 => "贵州", 53 => "云南", 54 => "西藏 ", 61 => "陕西", 62 => "甘肃", 63 => "青海", 64 => "宁夏", 65 => "新疆", 71 => "台湾", 81 => "香港", 82 => "澳门", 91 => "国外 "];
        $tip = "";
        $match = "/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/";
        $pass = true;
        if (!$card || !preg_match($match, $card)) {
            //身份证格式错误
            $pass = false;
        } else if (!$city[substr($card, 0, 2)]) {
            //地址错误
            $pass = false;
        } else {
            //18位身份证需要验证最后一位校验位
            if (strlen($card) == 18) {
                $card = str_split($card);
                //∑(ai×Wi)(mod 11)
                //加权因子
                $factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                //校验位
                $parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                $sum = 0;
                $ai = 0;
                $wi = 0;
                for ($i = 0; $i < 17; $i++) {
                    $ai = $card[$i];
                    $wi = $factor[$i];
                    $sum += $ai * $wi;
                }
                $last = $parity[$sum % 11];
                if ($parity[$sum % 11] != $card[17]) {
//                        $tip = "校验位错误";
                    $pass = false;
                }
            } else {
                $pass = false;
            }
        }
        if (!$pass) return false;/* 身份证格式错误*/
        return true;/* 身份证格式正确*/
    }

    //记录日志
    public function addLog($data){
        $request= Request::instance();
        $data['controller'] = $request->controller();
        $data['methods'] = $request->action();
        $data['addtime'] = time();
        $data['ip'] = request()->ip();
        $thisWechat = Session::get("thisWechat");
        $data['uniacid'] = empty($thisWechat['id'])?0:$thisWechat['id'];
        Db::name("admin_user_log")->insert($data);
    }

    //记录账户明细
    public function createlog($data){
        $data['addtime'] = time();
        $data['auto'] = "web";
        Db::name("admin_fans_log")->insert($data);
    }


    public function substr_cut($user_name){
        $strlen     = mb_strlen($user_name, 'utf-8');
        $firstStr     = mb_substr($user_name, 0, 1, 'utf-8');
        $lastStr     = mb_substr($user_name, -1, 1, 'utf-8');
        return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
    }


    public function request_post($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $curl = curl_init();//初始化curl
        curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($curl);//运行curl
        curl_close($curl);
        return $data;
    }

    //调用人脸识别
    public function fance($access_token,$bodys){
        $token =$access_token;
        $url = 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=' . $token;
        $res = $this->request_post($url, $bodys);
        $res = json_decode($res,true);
        return $res;
    }


    public function baiApi(){
        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        $post_data['grant_type']       = 'client_credentials';
        $post_data['client_id']      = '7sRu0qPIE2Qf2SPuDDPeUhm9';
        $post_data['client_secret'] = 'UnDW0ipU7UjDh7eznGq7Yy1XFH6wd9af';
        $o = "";
        foreach ( $post_data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);
        $res = $this->request_post($url, $post_data);
        $res = json_decode($res,true);
        return $res;
    }

}